package com.xingchi.tornado.security.context;

import com.xingchi.tornado.core.utils.RequestUtils;
import com.xingchi.tornado.security.constants.SecurityConstants;
import com.xingchi.tornado.security.model.IUser;
import com.xingchi.tornado.security.model.LoginData;
import lombok.Getter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 请求上下文对象
 *
 * @author xiaoya
 * @date 2024/10/18 15:40
 */
@Getter
public class RequestContext {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private ServletContext servletContext;
    private HttpSession session;

    @lombok.Setter
    private LoginData<? extends IUser> loginData;
    private String ip;
    private String userAgent;
    private String sessionId;

    private static final ThreadLocal<RequestContext> CONTEXT = ThreadLocal.withInitial(RequestContext::new);

    public static void init(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
        RequestContext context = new RequestContext();
        context.request = request;
        context.response = response;
        context.servletContext = servletContext;
        context.session = request.getSession(false);
        if (context.session != null) {
            context.loginData = getLoginData(context.session);
            context.sessionId = context.session.getId();
        }
        context.ip = context.loginData.getIp();
        context.userAgent = context.loginData.getUserAgent();
        CONTEXT.set(context);
    }

    public static RequestContext getContext() {
        return CONTEXT.get();
    }

    public static void clear() {
        CONTEXT.remove();
    }

    public static LoginData<?> getLoginData(HttpSession session) {
        Object loginData = session.getAttribute(SecurityConstants.LOGIN_DATA);
        if (loginData == null) {
            return LoginData.initLoginData();
        }
        return (LoginData<?>) loginData;
    }

    public static String getIp() {
        return getContext().ip;
    }

    public static String getUserAgent() {
        return getContext().userAgent;
    }

    public static <T> T getObj(Class<T> clazz) {
        return RequestUtils.getObj(clazz);
    }

    public static Long getUserId() {
        return getContext().loginData.getUserId();
    }

    public static String getUsername() {
        return getContext().loginData.getUsername();
    }

    public static String getName() {
        return getContext().loginData.getName();
    }

    public static String getSessionId() {
        return getContext().sessionId;
    }

}
